package com.pattern.responsibilityChain;

/**
 * @author Mr.yuan
 * @version v1.0
 * @date 2019/8/2 11:07
 **/
public class ResponsibilityChainPattern {
    public static void main(String[] args) {

        AbstractLogger loggerChain = getLoggerChain();
        loggerChain.logMessage(AbstractLogger.info, "this is info log");
        System.out.println("===");
        loggerChain.logMessage(AbstractLogger.debug, "this is debug log");
        System.out.println("===");
        loggerChain.logMessage(AbstractLogger.error, "this is error log");
    }

    private static AbstractLogger getLoggerChain() {
        AbstractLogger infoLogger = new InfoLogger(AbstractLogger.info);
        AbstractLogger debugLogger  = new DebugLogger(AbstractLogger.debug);
        AbstractLogger errorLogger = new ErrorLogger(AbstractLogger.error);
        errorLogger.setNextLogger(debugLogger);
        debugLogger.setNextLogger(infoLogger);
        return errorLogger;
    }

    private static abstract class AbstractLogger{
        private static int info=1;
        private static int debug=2;
        private static int error=3;
        protected int level;
        private AbstractLogger nextLogger;

        public void setNextLogger(AbstractLogger nextLogger) {
            this.nextLogger = nextLogger;
        }
        private void logMessage(int level,String message){
            if (this.level <= level){
                write(message);
            }
            if (null != nextLogger){
                nextLogger.logMessage(level, message);
            }
        }
        protected abstract void write(String message);
    }

    private static class InfoLogger extends AbstractLogger{

        public InfoLogger(int level) {
            this.level = level;
        }

        @Override
        protected void write(String message) {
            System.out.println("info log:"+message);
        }
    }
    private static class DebugLogger extends AbstractLogger{

        public DebugLogger(int level) {
            this.level = level;
        }

        @Override
        protected void write(String message) {
            System.out.println("debug log:"+message);
        }
    }
    private static class ErrorLogger extends AbstractLogger{

        public ErrorLogger(int level) {
            this.level = level;
        }

        @Override
        protected void write(String message) {
            System.out.println("error log:"+message);
        }
    }


}
